package top.ezzz.util.processtype;

import cn.hutool.system.oshi.OshiUtil;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import top.ezzz.model.ProcessInfo;

import java.util.ArrayList;
import java.util.List;

public class PortProcess implements TypeInterface {
    @Override
    public List<ProcessInfo> getProcessList() {
        OperatingSystem system = OshiUtil.getOs();
        // 只获取前50个最活跃的进程，避免扫描所有进程
        List<OSProcess> processes = system.getProcesses();
        List<ProcessInfo> result = new ArrayList<>();
        
        for (OSProcess process : processes) {
            try {
                String name = process.getName();
                if (name == null) continue;
                
                String nameLower = name.toLowerCase();
                String cmd = process.getCommandLine();
                String cmdLower = cmd != null ? cmd.toLowerCase() : "";
                
                // 识别网络相关进程
                if (!nameLower.contains("http") && !nameLower.contains("web") && 
                    !nameLower.contains("server") && !nameLower.contains("service") &&
                    !nameLower.contains("nginx") && !nameLower.contains("apache") &&
                    !nameLower.contains("tomcat") && !nameLower.contains("jetty") &&
                    !nameLower.contains("node") && !nameLower.contains("mysql") &&
                    !nameLower.contains("postgres") && !nameLower.contains("redis") &&
                    !nameLower.contains("mongodb") && !nameLower.contains("elasticsearch") &&
                    !cmdLower.contains(":8080") && !cmdLower.contains(":3000") &&
                    !cmdLower.contains(":3306") && !cmdLower.contains(":5432") &&
                    !cmdLower.contains(":6379") && !cmdLower.contains(":9200")) {
                    continue;
                }
                
                // 获取实时进程信息
                result.add(new ProcessInfo()
                        .setPid(process.getProcessID())
                        .setName(name)
                        .setCommandLine(cmd != null ? cmd : "")
                        .setCpuUsage(0.0) // 暂时设为0，后续可以添加实时计算
                        .setMemoryUsage(process.getResidentSetSize())
                        .setStartTime(process.getStartTime())
                        .setUpTime(process.getUpTime())
                );
            } catch (Exception e) {
                // 跳过有问题的进程
                continue;
            }
        }
        
        return result;
    }
}
